import { action, observable, reaction } from 'mobx';
import { useLocalObservable } from 'mobx-react-lite';

import { router } from '@/routes';

import { layoutStore } from '../layout';

export type TabsData = RouteData & {
  id: string;
};

export const tabsStore = observable({
  list: [] as TabsData[],
  activeTab: null as null | TabsData,

  /** 校验指定标签两侧是否有可关闭的标签 */
  checkCloseOtherSide: action((tab: TabsData): boolean => {
    return tabsStore.list.some((item) => item.id !== tab.id);
  }),
  /** 校验指定标签左侧是否有可关闭的标签 */
  checkCloseLeftSide: action((tab: TabsData): boolean => {
    let flag = true;
    if (tab.id === tabsStore.list[0]?.id) {
      flag = false;
    } else {
      const index = tabsStore.list.findIndex((item) => item.id === tab.id);
      flag = tabsStore.list.some((item, i) => {
        return i < index && item.id !== tab.id;
      });
    }
    return flag;
  }),
  /** 校验指定标签右侧是否有可关闭的标签 */
  checkCloseRightSide: action((tab: TabsData): boolean => {
    let flag = true;
    if (tab.id === tabsStore.list[tabsStore.list.length - 1]?.id) {
      flag = false;
    } else {
      const index = tabsStore.list.findIndex((item) => item.id === tab.id);
      flag = tabsStore.list.some((item, i) => {
        return i >= index && item.id !== tab.id;
      });
    }
    return flag;
  }),
  closeTab: action((tab: TabsData, action: 'self' | 'others' | 'left' | 'right') => {
    const index = tabsStore.list.findIndex((t) => t.id === tab.id);
    const activeIndex = tabsStore.list.findIndex((t) => t.id === tabsStore.activeTab?.id);

    let newTabs = [...tabsStore.list];
    let newActiveIndex = activeIndex;

    switch (action) {
      case 'self':
        // 关闭当前标签
        if (index !== -1) {
          newTabs.splice(index, 1);
          // 如果关闭的是当前活动标签
          if (tab.id === tabsStore.activeTab?.id) {
            if (newTabs.length === 0) {
              // 没有标签页
              newActiveIndex = -1;
            } else if (index === activeIndex && index === newTabs.length) {
              // 如果关闭的是最后一个标签
              newActiveIndex = index - 1;
            } else if (index !== activeIndex) {
              // 如果关闭的不是活动标签，保持当前活动标签不变
              newActiveIndex = tabsStore.list.findIndex((t) => t.id === tabsStore.activeTab?.id);
            }
          }
        }
        break;
      case 'others':
        // 关闭所有其他标签，保留当前标签
        if (index !== -1) {
          newTabs = [tab];
          newActiveIndex = 0; // 仅剩下的标签设为活动
        }
        break;
      case 'left':
        // 关闭左侧所有标签，保留当前标签及右侧标签
        if (index > 0) {
          newTabs.splice(0, index);
          newActiveIndex = newTabs.findIndex((t) => t.id === tab.id);
        }
        break;
      case 'right':
        // 关闭右侧所有标签，保留当前标签及左侧标签
        if (index !== -1) {
          newTabs.splice(index + 1, tabsStore.list.length - index - 1);
          newActiveIndex = newTabs.findIndex((t) => t.id === tab.id);
        }
        break;
      default:
        throw new Error('Invalid action specified');
    }

    tabsStore.list = newTabs;

    if (newActiveIndex >= 0 && newActiveIndex < newTabs.length) {
      tabsStore.activeTab = newTabs[newActiveIndex];
    } else if (newTabs.length > 0) {
      console.log(1);
      tabsStore.activeTab = newTabs[0];
    } else {
      tabsStore.activeTab = null;
    }

    if (tabsStore.activeTab) {
      router.navigate(tabsStore.activeTab?.path as string);
    }
  })
});

// 根据pathname同步
const sync = (matchRoute = layoutStore.matchRoute) => {
  if (
    matchRoute &&
    matchRoute.path &&
    !/\*/.test(matchRoute.path) &&
    matchRoute.element &&
    !matchRoute.hideTab
  ) {
    const tab = {
      ...matchRoute,
      id: matchRoute.path
    };

    const find = tabsStore.list.find((t) => t.id === tab.id);

    if (!find) {
      tabsStore.list.push(tab);
    }

    tabsStore.activeTab = tab;
  }
};

reaction(
  () => layoutStore.matchRoute,
  (matchRoute) => {
    sync(matchRoute);
  },
  {
    fireImmediately: true
  }
);

export const useTabsStore = () => useLocalObservable(() => tabsStore);
